package cn.aixuegao.common.base.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.plugins.Page;

import cn.aixuegao.common.base.entity.PageContainer;
import cn.aixuegao.common.constant.Const;
import cn.aixuegao.common.result.Response;
import cn.aixuegao.common.result.ResponseData;
import cn.aixuegao.common.result.ResultMsg;
import cn.aixuegao.model.user.User;

/**
 * controller基类
 * @author hxy
 * @date 2018/3/22
 */
public abstract class BaseController {
	
	/**
	 * @return 返回request 请求对象
	 */
	protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
	
	/**
	 * @param msg
	 * @return 返回前端的简单的状态码和状态信息
	 */
	protected Response resultMsg(ResultMsg msg){
    	return new Response(msg);
    }
	
	/**
	 * 
	 * @param msg
	 * @param obj
	 * @return 返回有数据的json对象
	 */
	protected ResponseData resultData(ResultMsg msg,Object obj){
    	return new ResponseData(msg, obj);
    }
	/**
	 * 
	 * @Title:BaseController
	 * @Description:
	 * @param msg
	 * @param page
	 * @param obj
	 * @return
	 */
	protected ResponseData resultPageData(Page page){
		if(!page.getRecords().isEmpty()) {
			PageContainer pageContainer = new PageContainer();
			try {
				BeanUtils.copyProperties(pageContainer,page);
			} catch (IllegalAccessException | InvocationTargetException e) {
				/**此处应该记录日志*/
				return new ResponseData(ResultMsg.FAILED,"");
			}
			pageContainer.setRecords(page.getRecords());
			return new ResponseData(ResultMsg.SUCCESS, pageContainer);
		}else {
			return resultData(ResultMsg.NO_DATA, "");
		}
			
	}
	/**
	 * 获取session
	 * @return
	 */
	protected HttpSession getSession() {
        return getRequest().getSession();
    }
	
	/**
	 * 设置session中的值
	 * @return
	 */
	protected void setSessionAttr(String key , Object obj) {
         getSession().setAttribute(key, obj);
    }
	
	/**
	 * 获取session中的值
	 * @return
	 */
	protected Object getSessionAttr(String key) {
		return getSession().getAttribute(key);
	}
	/**
	 * 
	 * @Title:BaseController
	 * @Description:
	 * @param key
	 * @return
	 */
	protected User getUser() {
		return (User)getSession().getAttribute(Const.SESSION_KEY);
	}
}
